package com.demo.message_retry;

import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.alibaba.fastjson2.JSON;
import com.demo.commons.MqCons;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = MqCons.BIZ_ERROR_QUEUE, durable = "true"), key = MqCons.BIZ_ERROR_KEY,
                exchange = @Exchange(value = MqCons.BIZ_ERROR_EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class MqErrorListener {

    /**
     * data: 对象类型必须是Object, 因为可能多个监听者body类型可能不同, 发送方可能传输的数据是String或者Byte类型 </br>
     * 如果这时你指定具体类型, 当前监听器将接收不到重试一定次数依旧失败的消息(body类型不同), 只能接收与子相匹配的body类型消息
     */
    @RabbitHandler
    public void onMessage(Object data, Channel channel, Message message) {
        try {
            log.info("异常队列消费, msg: {}, x-original-routingKey: {}, x-exception-message: {}, x-original-exchange: {}",
                    JSON.toJSONString(new String(message.getBody())),
                    message.getMessageProperties().getHeader("x-original-routingKey"),
                    message.getMessageProperties().getHeader("x-exception-message"),
                    message.getMessageProperties().getHeader("x-original-exchange"));
            log.info("告警发送短信成功...");
        } catch (Exception e) {
            log.error("消费失败: {}", e.getMessage());
            throw new BizException(-1, "mq消费失败");
        }
    }
}
